package com.project651.www;

import java.util.Arrays;

import com.project651.www.JoinGameService.JoinGameServiceBinder;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class JoinGameKeyboard extends Activity implements OnClickListener {
	EditText letterField;
	EditText ipAddressField;
	TextView hiddenWordView;
	TextView attemptedLettersView;
	Button ipSubmit;
	CharSequence missedText;
	CharSequence hiddenWord;
	CharSequence secretText;
	GameStates gameState;
	boolean lettersFound[];
	static private final String TAG = "Client";
	static public final int BUFFERSIZE = 512;
	boolean joinGameBound = false;
	private JoinGameService joinGameService;
	Intent intentJoinGameService;
	private boolean connected = false;
	static private WordNotifier wordNotifier;
	
	
	
	public enum GameStates {
		NOTHING,
		HEAD,
		BODY,
		ONELEG,
		TWOLEGS,
		ONEARM,
		TWOARMS,
		GAMEOVER,
		WIN
	}
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.joingamekeyboard);
        
        hiddenWordView = (TextView) findViewById(R.id.hiddenword);
        attemptedLettersView = (TextView) findViewById(R.id.attemptedletters);
        ipAddressField = (EditText) findViewById(R.id.ipfield);
        
        missedText = "Incorrect Letters:";
        attemptedLettersView.setText(missedText);
        
        //assign hidden word
        Bundle b = getIntent().getExtras();
        if (b != null && b.containsKey("secretWord")) {
        	hiddenWord = b.getCharSequence("secretWord");
        	//make boolean array to check if entire word has been figured out
            lettersFound = new boolean[hiddenWord.length()];
            Arrays.fill(lettersFound, false);
            
            secretText = "";
            for(int i = 0; i < hiddenWord.length(); i++) {
            	secretText = secretText.toString() + "_";
            	if(i != hiddenWord.length()) {
            		secretText = secretText.toString() + " ";
            	}
            }
            hiddenWordView.setText(secretText);
        } else {
        	hiddenWord = "";
        	secretText = "Waiting on word...";
        	hiddenWordView.setText(secretText);
        }
        
        
        //attach buttons
        ((Button) findViewById(R.id.a)).setOnClickListener(this);
        ((Button) findViewById(R.id.b)).setOnClickListener(this);
        ((Button) findViewById(R.id.c)).setOnClickListener(this);
        ((Button) findViewById(R.id.d)).setOnClickListener(this);
        ((Button) findViewById(R.id.e)).setOnClickListener(this);
        ((Button) findViewById(R.id.f)).setOnClickListener(this);
        ((Button) findViewById(R.id.g)).setOnClickListener(this);
        ((Button) findViewById(R.id.h)).setOnClickListener(this);
        ((Button) findViewById(R.id.i)).setOnClickListener(this);
        ((Button) findViewById(R.id.j)).setOnClickListener(this);
        ((Button) findViewById(R.id.k)).setOnClickListener(this);
        ((Button) findViewById(R.id.l)).setOnClickListener(this);
        ((Button) findViewById(R.id.m)).setOnClickListener(this);
        ((Button) findViewById(R.id.n)).setOnClickListener(this);
        ((Button) findViewById(R.id.o)).setOnClickListener(this);
        ((Button) findViewById(R.id.p)).setOnClickListener(this);
        ((Button) findViewById(R.id.q)).setOnClickListener(this);
        ((Button) findViewById(R.id.r)).setOnClickListener(this);
        ((Button) findViewById(R.id.s)).setOnClickListener(this);
        ((Button) findViewById(R.id.t)).setOnClickListener(this);
        ((Button) findViewById(R.id.u)).setOnClickListener(this);
        ((Button) findViewById(R.id.v)).setOnClickListener(this);
        ((Button) findViewById(R.id.w)).setOnClickListener(this);
        ((Button) findViewById(R.id.x)).setOnClickListener(this);
        ((Button) findViewById(R.id.y)).setOnClickListener(this);
        ((Button) findViewById(R.id.z)).setOnClickListener(this);
        
        (ipSubmit = (Button) findViewById(R.id.ipsubmit)).setOnClickListener(this);
        
        gameState = GameStates.NOTHING;
        
        // register notifier
        wordNotifier = new WordNotifier();
        registerReceiver(wordNotifier, new IntentFilter(JoinGameService.CLIENTSERVER));
        
        // start service
        intentJoinGameService = new Intent(this, JoinGameService.class);
        bindService(intentJoinGameService, mConnection, Context.BIND_AUTO_CREATE);
        startService(intentJoinGameService);
    }
    
	public void onClick(View arg0) {
		if (arg0.getId() == R.id.ipsubmit) {
			connectToServer();
		} else if(gameState != GameStates.WIN && gameState != GameStates.GAMEOVER){ 
			char letter = '\0';
			switch(arg0.getId()) {
			case R.id.a:
				letter = 'A';
				break;
			case R.id.b:
				letter = 'B';
				break;
			case R.id.c:
				letter = 'C';
				break;
			case R.id.d:
				letter = 'D';
				break;
			case R.id.e:
				letter = 'E';
				break;
			case R.id.f:
				letter = 'F';
				break;
			case R.id.g:
				letter = 'G';
				break;
			case R.id.h:
				letter = 'H';
				break;
			case R.id.i:
				letter = 'I';
				break;
			case R.id.j:
				letter = 'J';
				break;
			case R.id.k:
				letter = 'K';
				break;
			case R.id.l:
				letter = 'L';
				break;
			case R.id.m:
				letter = 'M';
				break;
			case R.id.n:
				letter = 'N';
				break;
			case R.id.o:
				letter = 'O';
				break;
			case R.id.p:
				letter = 'P';
				break;
			case R.id.q:
				letter = 'Q';
				break;
			case R.id.r:
				letter = 'R';
				break;
			case R.id.s:
				letter = 'S';
				break;
			case R.id.t:
				letter = 'T';
				break;
			case R.id.u:
				letter = 'U';
				break;
			case R.id.v:
				letter = 'V';
				break;
			case R.id.w:
				letter = 'W';
				break;
			case R.id.x:
				letter = 'X';
				break;
			case R.id.y:
				letter = 'Y';
				break;
			case R.id.z:
				letter = 'Z';
				break;
			}
				
			// CHECK IF LETTER IN WORD
			boolean wasInWord = false;
			for (int i = 0; i < hiddenWord.length(); i++) {
				if (letter == hiddenWord.charAt(i)) {
					secretText = secretText.subSequence(0, 2*i).toString()
						+ hiddenWord.charAt(i)
						+ secretText.subSequence(2*i+1, secretText.length()).toString();
					wasInWord = true;
					//lettersFound[i] = true;
				}
			}
			//display new secret phrase
			hiddenWordView.setText(secretText);
			//END CHECK IF LETTER IN WORD
			
			// IF THE LETTER IS NOT IN THE WORD
			if(!wasInWord) {
				RelativeLayout background = (RelativeLayout) findViewById(R.id.joinbackground);
				switch(gameState) {
				case NOTHING:
					background.setBackgroundResource(R.drawable.head);
					gameState = GameStates.HEAD;
					break;
				case HEAD:
					background.setBackgroundResource(R.drawable.body);
					gameState = GameStates.BODY;
					break;
				case BODY:
					background.setBackgroundResource(R.drawable.oneleg);
					gameState = GameStates.ONELEG;
					break;
				case ONELEG:
					background.setBackgroundResource(R.drawable.twolegs);
					gameState = GameStates.TWOLEGS;
					break;
				case TWOLEGS:
					background.setBackgroundResource(R.drawable.onearm);
					gameState = GameStates.ONEARM;
					break;
				case ONEARM:
					background.setBackgroundResource(R.drawable.twoarms);
					gameState = GameStates.TWOARMS;
					break;
				case TWOARMS:
					background.setBackgroundResource(R.drawable.gameover);
					gameState = GameStates.GAMEOVER;
					hiddenWordView.setText("Solution: " + hiddenWord);
					int status = 1;
					joinGameService.sendStatus(status);
					break;
				}
			
				missedText = missedText.toString() + " " + letter;
				attemptedLettersView.setText(missedText);
			}
			// END IF LETTER NOT IN WORD
			else {
				boolean allTrue = true;
				for(int i = 0; i < secretText.length(); i++) {
					if (secretText.charAt(i) == '_') allTrue = false;
				}
				if(allTrue) {
					//winning background
					RelativeLayout background = (RelativeLayout) findViewById(R.id.joinbackground);
					background.setBackgroundResource(R.drawable.win);
					gameState = GameStates.WIN;
					int status = 0;
					joinGameService.sendStatus(status);
				}
			}
		}
	}

	private class WordNotifier extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			Bundle b = intent.getExtras();
			CharSequence word = b.getCharSequence("Word");
			
			int j = 0, endOfWord = -1;
			while (endOfWord == -1 && j < word.length()){
				if (word.charAt(j) == '\0') endOfWord = j;
				j++;
			}
			
			hiddenWord = word.subSequence(0, endOfWord).toString().toUpperCase();
			//initialize word and game
			secretText = "";
			
	        for(int i = 0; i < hiddenWord.length(); i++) {
	        	secretText = secretText.toString() + "_";
	        	if(i != hiddenWord.length()) {
	        		secretText = secretText.toString() + " ";
	        	}
	        }
	        hiddenWordView.setText(secretText);
		}
	}
	
	private void connectToServer() {
		connected = true;
		String addr = ipAddressField.getText().toString();
		joinGameService.attemptConnection(addr);
		// made the ip address input and the ip submit button disappear
		ipAddressField.setVisibility(View.GONE);
		ipSubmit.setVisibility(View.GONE);
	}
	
	private ServiceConnection mConnection = new ServiceConnection() {

		public void onServiceDisconnected(ComponentName name) {
			joinGameBound = false;
		}

		public void onServiceConnected(ComponentName name, IBinder service) {
			JoinGameServiceBinder binder = (JoinGameServiceBinder) service;
			joinGameService = binder.getService();
			joinGameBound = true;
		}
	};
}